﻿using ETask.Api.Dtos;
using ETask.Api.Mappers;
using ETask.Api.Models;
using ETask.Api.Repositories;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using LoginRequest = ETask.Api.Dtos.LoginRequest;
using ETask.Api.Data;
using System.Text;
using AutoMapper;

namespace ETask.Api.Services
{
    public class UserService : GenericService<User, UserDto, CreateUserDto, UpdateUserDto>, IUserService
    {
        private readonly IUserRepository _userRepository;

        private readonly IConfiguration _config;

        public UserService(IConfiguration config, IUserRepository repository, GenericMapper<User, UserDto, CreateUserDto, UpdateUserDto> mapper) : base(repository, mapper)
        {
            _config = config;
            _userRepository = repository;
        }

        public async Task<ApiResponse> UserInfo()
        {
            try
            {
                LoginUser loginUser = UserContext.CurrentUser;
                if (loginUser == null)
                {
                    return ApiResponse.Fail(401, "用户未登录");
                }

                UserDto user = await _userRepository.GetByInfoByAccount(loginUser.Account);
                if (user == null)
                {
                    return ApiResponse.Fail(404, "用户信息不存在");
                }

                return ApiResponse.Ok(user);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"获取用户信息失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> Login(LoginRequest loginRequest)
        {
            try
            {
                User user = await _userRepository.GetByAccount(loginRequest.Account);
                if (user == null) 
                {
                    return ApiResponse.Fail(400, "账户不存在");
                }
                
                string encryptedPassword = Md5Helper.Encrypt32(loginRequest.Password);
                if (!encryptedPassword.Equals(user.Password)) 
                {
                    return ApiResponse.Fail(400, "密码错误");
                }
                string token = GenerateJwtToken(user);
                UserDto userInfo = await _userRepository.GetByInfoByAccount(user.Account);
                return ApiResponse.Ok(new
                {
                    token = token,
                    user = userInfo,
                });
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"登录失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> ResetPassword(ResetPasswordDto passwordDto)
        {
            try
            {
                LoginUser loginUser = UserContext.CurrentUser;
                if (loginUser == null)
                {
                    return ApiResponse.Fail(401, "用户未登录");
                }

                User user = await _userRepository.GetByIdAsync(loginUser.Id);
                if (user == null)
                {
                    return ApiResponse.Fail(404, "用户不存在");
                }

                passwordDto.OldPassword = Md5Helper.Encrypt32(passwordDto.OldPassword);
                if (!user.Password.Equals(passwordDto.OldPassword))
                {
                    return ApiResponse.Fail(400, "原密码错误");
                }
                
                string newPassword = Md5Helper.Encrypt32(passwordDto.NewPassword);
                user.Password = newPassword;
                await _userRepository.UpdateAsync(user);
                return ApiResponse.Ok("密码修改成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"密码修改失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> UpdateUserInfo(UpdateUserDto updateUserDto)
        {
            try
            {
                LoginUser loginUser = UserContext.CurrentUser;
                if (loginUser == null)
                {
                    return ApiResponse.Fail(401, "用户未登录");
                }

                User user = await _userRepository.GetByAccount(loginUser.Account);
                if (user == null)
                {
                    return ApiResponse.Fail(404, "用户不存在");
                }

                // 更新用户信息
                user.Email = updateUserDto.Email;
                user.Phone = updateUserDto.Phone;
                user.UpdatedAt = DateTime.Now;

                await _userRepository.UpdateAsync(user);
                return ApiResponse.Ok("用户信息修改成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"用户信息修改失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetList(UserListParams listParams)
        {
            var pageList = await _userRepository.GetListAsync(listParams);
            return ApiResponse.Ok(pageList);
        }

        private string GenerateJwtToken(User userInfo)
        {
            var jwtSettings = _config.GetSection("Jwt");
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings["Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var issuer = jwtSettings["Issuer"];
            var audience = jwtSettings["Audience"];

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()),
                new Claim(ClaimTypes.Name, userInfo.Name),
                new Claim("account", userInfo.Account),
            };

            var token = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                expires: DateTime.UtcNow.AddHours(2),
                signingCredentials: creds
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        public async Task<ApiResponse> Register(CreateUserDto createUser)
        {
            try
            {
                // 检查用户是否存在
                string account = createUser.Account;
                User existingUser = await _userRepository.GetByAccount(account);
                if (existingUser != null)
                {
                    return ApiResponse.Fail(400, "用户已存在");
                }
                User newUser = _mapper.ToEntity(createUser);
                
                newUser.Password = Md5Helper.Encrypt32(createUser.Password);
                newUser.CreatedAt = DateTime.Now;
                newUser.UpdatedAt = DateTime.Now;
                
                await _userRepository.AddAsync(newUser);
                return ApiResponse.Ok("注册成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"注册失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> ResetUserPassword(ResetPasswordDto passwordDto)
        {
            try
            {
     
                User user = await _userRepository.GetByIdAsync(passwordDto.UserId.Value);
                if (user == null)
                {
                    return ApiResponse.Fail(404, "用户不存在");
                }
                string newPassword = Md5Helper.Encrypt32(passwordDto.NewPassword);
                user.Password = newPassword;
                await _userRepository.UpdateAsync(user);
                return ApiResponse.Ok("密码修改成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"密码修改失败: {ex.Message}");
            }
        }
    }
}
